package com.autumn.aitraffic.util;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class ExcelUtil<T> {

    // excel文件后缀
    private final static String EXCE_L2003 = "xls";
    private final static String EXCEL_2007 = "xlsx";

    // 校验文件后缀是否为 xls、xlsx
    public static boolean checkExcelExtension(MultipartFile excel) {
        String filename = excel.getOriginalFilename();
        if (StringUtil.isBlank(filename)) {
            log.info("【校验Excel文件后缀】Excel文件名为空");
            return false;
        }
        int index = filename.lastIndexOf(".");
        if (index == -1) {
            log.info("【校验Excel文件后缀】Excel文件名中没有点号");
            return false;
        }
        String extension = filename.substring(index + 1);
        return Arrays.asList(EXCE_L2003, EXCEL_2007).contains(extension);
    }

    // 读取excel文件
    public List<T> simpleExcelRead(String filePath, Class<T> clazz) {
        ExcelListener<T> excelListener = new ExcelListener();
        EasyExcel.read(filePath, clazz, excelListener).sheet().doRead();
        List<T> dataList = excelListener.getDataList();
        return dataList;
    }
    // 读取excel文件无需路径
    public List<T> ExcelRead(MultipartFile file) {
        ExcelListener<T> excelListener = new ExcelListener();
        EasyExcel.read(multipartFile2File(file),excelListener).sheet().doRead();
        List<T> dataList = excelListener.getDataList();
        return dataList;
    }

    //multiFile转File
    public File multipartFile2File (MultipartFile multipartFile) {
        // 创建临时文件
        String path = "export/demo.xlsx";
        File file = new File(path);
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            // 获取文件输入流
            inputStream = multipartFile.getInputStream();

            if (!file.exists()) {
                file.createNewFile();
            }
            // 创建输出流
            outputStream = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int len;
            // 写入到创建的临时文件
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关流
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (outputStream != null) {
                    inputStream.close();
                }
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return file;
    }

}
